<template>
	<div class="layout-padding-auto layout-padding-view">
		<el-form ref="formRef" :model="form" label-width="140px" :rules="rules" status-icon label-position="left"
			v-loading="loading">
			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>{{ form.id ? '修改优惠券' : '新增优惠券' }}</span>
					</div>
				</template>
				<el-form-item label="优惠券名称" prop="couponName">
					<el-input v-model="form.couponName" maxlength="50" show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="有效时间" prop="datatimes">
					<el-date-picker v-model="form.datatimes" :disabled="form.id" type="datetimerange" range-separator="-"
						start-placeholder="活动开始时间" end-placeholder="活动结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
				<el-form-item label="优惠形式" prop="couponType">
					<el-radio-group v-model="form.couponType" :disabled="form.id">
						<el-radio label="1">指定金额</el-radio>
						<el-radio label="2">折扣</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="优惠金额" prop="amount" v-if="form.couponType == '1'">
					<el-input-number v-model="form.amount" :disabled="form.id" :min="0.01" :precision="2"
						:controls="false" />
				</el-form-item>
				<el-form-item label="折扣" prop="discount" v-if="form.couponType == '2'">
					<el-input-number v-model="form.discount" :disabled="form.id" :min="0.1" :max="9.9" :precision="1"
						:controls="false" />
				</el-form-item>
				<el-form-item label="使用门槛" prop="threshold">
					<div style="display: flex">
						<span style="padding: 0px 8px">满：</span>
						<el-input-number v-model="form.threshold" :disabled="form.id" :precision="2"
							:controls="false"></el-input-number>
						<span style="padding: 0px 8px; width: 120px">可以使用</span>
					</div>
					<div>
						<p style="color: #f56c6c">0元表示无门槛</p>
					</div>
				</el-form-item>
				<el-form-item label="发行数量" prop="totalNum">
					<el-input-number v-model="form.totalNum" :disabled="form.id" :min="1" :precision="0"
						:controls="false" />
				</el-form-item>
				<el-form-item label="领取限制" prop="receiveCount">
					<div style="display: flex">
						<span style="padding: 0px 8px; width: 120px">每人限领：</span>
						<el-input-number v-model="form.receiveCount" :disabled="form.id" :precision="0" :controls="false" />
						<span style="padding: 0px 8px; width: 120px">张</span>
					</div>
				</el-form-item>
				<el-form-item label="使用说明" prop="useDescription">
					<el-input v-model="form.useDescription" maxlength="100" placeholder="请输入使用范围" show-word-limit
						type="textarea" />
				</el-form-item>
				<el-form-item label="可用范围" prop="useRange">
					<el-radio-group v-model="form.useRange" :disabled="form.id">
						<el-radio label="1">全部商品</el-radio>
						<el-radio label="2">指定商品</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="指定商品" prop="spuId" v-if="form.useRange == '2'">
					<el-button type="success" v-if="!form.id" link @click="selectSpu">选择商品</el-button>
					<el-table v-if="form.couponGoodsList" :data="form.couponGoodsList" style="width: 100%">
						<el-table-column prop="spuUrls" label="图片" width="300">
							<template #default="scope">
								<el-image style="width: 50px; height: 50px" :src="scope.row.spuUrls[0]"
									:preview-src-list="scope.row.spuUrls" fit="cover" :preview-teleported="true"></el-image>
							</template>
						</el-table-column>
						<el-table-column prop="spuName" label="商品名" show-overflow-tooltip />
						<el-table-column label="操作" width="200" align="center">
							<template #default="scope">
								<el-button :disabled="form.id" link type="danger" icon="delete"
									@click="del(scope.row.id, scope.row.index)"> 删除 </el-button>
							</template>
						</el-table-column>
					</el-table>

					<SelectGoods ref="selectGoods" :limitNum="10" @currentRow="spuCurrent"></SelectGoods>
				</el-form-item>
				<el-form-item label="启用状态" prop="status">
					<el-radio-group v-model="form.status">
						<el-radio label="0">正常</el-radio>
						<el-radio label="1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-card>
		</el-form>
		<div class="goods-footer">
			<div class="submit-button">
				<div>
					<el-button @click="handleClose">关 闭</el-button>
					<el-button type="primary" :disabled="loading" @click="submitForm(formRef)">确 认</el-button>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang="ts">
import { defineComponent, defineAsyncComponent, ref, reactive, toRefs } from 'vue';
import { addObj, editObj, getById } from '/@/api/mall/couponinfo';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, FormInstance } from 'element-plus';
interface DataState {
	form: {
		id: string | undefined;
		couponName: string;
		status: string;
		useRange: string;
		amount: number;
		discount: number;
		threshold: number;
		totalNum: number;
		receiveCount: number;
		useDescription: string;
		datatimes: Array<any>;
		couponType: string;
		couponGoodsList: Array<any>;
		receiveStartedAt: string;
		receiveEndedAt: string;
	};
	rules: any;
}
export default defineComponent({
	components: { SelectGoods: defineAsyncComponent(() => import('/@/components/selectGoods/index.vue')) },
	emits: ['initPage'],
	setup() {
		const data = reactive<DataState>({
			form: {
				id: undefined,
				couponName: '',
				status: '',
				useRange: '',
				amount: 0,
				discount: 0,
				threshold: 0,
				totalNum: 0,
				receiveCount: 0,
				useDescription: '',
				datatimes: [],
				couponType: '1',
				couponGoodsList: [],
				receiveStartedAt: '',
				receiveEndedAt: '',
			},
			rules: {
				couponName: [
					{
						required: true,
						message: '请输入优惠券名称',
						trigger: 'change',
					},
				],
				status: [
					{
						required: true,
						message: '请选择优惠券状态',
						trigger: 'change',
					},
				],

				datatimes: [
					{
						required: true,
						message: '请选择有效时间',
						trigger: 'change',
					},
				],
				couponType: [
					{
						required: true,
						message: '请选择优惠形式',
						trigger: 'change',
					},
				],
				discount: [
					{
						required: true,
						message: '请输入折扣',
						trigger: 'change',
					},
				],
				amount: [
					{
						required: true,
						message: '请输入优惠金额（元）',
						trigger: 'change',
					},
				],
				threshold: [
					{
						required: true,
						message: '请输入使用门槛（元）',
						trigger: 'change',
					},
				],
				totalCount: [
					{
						required: true,
						message: '请输入发行数量',
						trigger: 'change',
					},
				],
				useRange: [
					{
						required: true,
						message: '请选择可用范围',
						trigger: 'change',
					},
				],
				useDescription: [
					{
						required: true,
						message: '请输入使用说明',
						trigger: 'change',
					},
				],
			},
		});
		const selectGoods = ref();
		const router = useRouter();
		const route = useRoute();
		const loading = ref(false);
		const formRef = ref();
		/**
		 * 关闭事件
		 */
		const handleClose = () => {
			resetForm(formRef.value);
			router.back();
		};
		/**
		 * 重置表单
		 */
		const resetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			data.form.id = undefined;
			loading.value = false;
			formEl.resetFields();
		};
		/**
		 * 提交按钮
		 */
		const submitForm = async (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					data.form.receiveStartedAt = data.form.datatimes[0];
					data.form.receiveEndedAt = data.form.datatimes[1];
					loading.value = true;
					if (data.form.id) {
						//修改
						edit();
					} else {
						//新增
						add();
					}
				}
			});
		};
		/**
		 * 新增
		 */
		const add = () => {
			addObj(data.form)
				.then((response) => {
					ElMessageBox.confirm('新增成功', '提示', {
						confirmButtonText: '继续添加',
						cancelButtonText: '返回列表',
						type: 'success',
					})
						.then(() => {
							resetForm(formRef.value);
						})
						.catch(() => {
							handleClose();
						});
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 修改
		 */
		const edit = () => {
			editObj(data.form)
				.then((response) => {
					ElMessageBox.confirm('修改成功', '提示', {
						confirmButtonText: '新增商品',
						cancelButtonText: '返回列表',
						type: 'success',
					})
						.then(() => {
							resetForm(formRef.value);
						})
						.catch(() => {
							handleClose();
						});
				})
				.catch(() => {
					loading.value = false;
				});
		};
		const initForm = () => {
			const { id }: any = route.query;
			if (id) {
				getDetail(id);
			}
		};
		const getDetail = (id: string) => {
			loading.value = true;
			// 修改
			getById(id)
				.then((response) => {
					loading.value = false;
					data.form = response.data.data;
					data.form.datatimes = [data.form.receiveStartedAt, data.form.receiveEndedAt];
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 选择商品
		 */
		const selectSpu = () => {
			selectGoods.value.dialog = true;
		};
		/**
		 * 删除
		 * @param id
		 */
		const del = (id: string, index: number) => {
			data.form.couponGoodsList.splice(index, 1);
		};
		const spuCurrent = (spuList: any) => {
			if (spuList) {
				let goodsSpuList: Array<any> = [];
				spuList.forEach((item: any) => {
					goodsSpuList.push({
						spuId: item.id,
						spuName: item.name,
						spuUrls: item.spuUrls,
					});
				});
				data.form.couponGoodsList = goodsSpuList;
			}
		};

		initForm();
		return {
			loading,
			formRef,
			selectGoods,
			del,
			selectSpu,
			submitForm,
			spuCurrent,
			handleClose,
			...toRefs(data),
		};
	},
});
</script>
<style lang="scss">
.goods-footer {
	padding: 10px;
	border-top: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
	background: #fff;

	.el-button {
		width: 200px;
	}

	.submit-button {
		text-align: center;
	}
}
</style>
